package io.kiki.sba.registry.server.clientInterface.scheduler.timertask;

import io.kiki.sba.registry.api.Server;
import io.kiki.sba.registry.api.exchange.DataExchanger;
import io.kiki.sba.registry.common.model.Tuple;
import io.kiki.sba.registry.server.clientInterface.bootstrap.Config;
import io.kiki.sba.registry.server.clientInterface.bootstrap.ExecutorManager;
import io.kiki.sba.registry.server.clientInterface.store.Publishers;
import io.kiki.sba.registry.server.clientInterface.store.Subscribers;
import io.kiki.sba.registry.server.clientInterface.store.Watchers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * The type Sync clients heartbeat task.
 */
public class SyncClientsHeartbeatTask {
    private static final Logger logger = LoggerFactory.getLogger(SyncClientsHeartbeatTask.class);

    @Autowired
    DataExchanger boltDataExchanger;

    @Autowired
    Config config;

    /**
     * store subscribers
     */
    @Autowired
    Subscribers subscribers;

    /**
     * store watchers
     */
    @Autowired
    Watchers watchers;

    /**
     * store publishers
     */
    @Autowired
    Publishers publishers;

    @Autowired
    ExecutorManager executorManager;

    @Scheduled(initialDelay = 60000, fixedRate = 60000)
    public void syncCount() {
        Tuple<Long, Long> countSub = subscribers.count();
        Tuple<Long, Long> countPub = publishers.count();
        Tuple<Long, Long> countSubW = watchers.count();

        int channelCount = 0;
        Server sessionServer = boltDataExchanger.getServer(config.getServerPort());
        if (sessionServer != null) {
            channelCount = sessionServer.getChannelCount();
        }

        Metrics.PUB_SUM.set(countPub.o2);
        Metrics.SUB_SUM.set(countSub.o2);
        Metrics.WAT_SUM.set(countSubW.o2);
        Metrics.CHANNEL_SUM.set(channelCount);

        logger.info("Subscriber count: {}, Publisher count: {}, Watcher count: {}, Connection count: {}, SubDataId={}, PubDataId={}, WatDataId={}", countSub.o2, countPub.o2, countSubW.o2, channelCount, countSub.o1, countPub.o1, countSubW.o1);
    }
}
